package middle.ground.http.config;

import com.google.common.collect.Maps;
import middle.ground.http.filter.XssFilter;
import middle.ground.http.interceptor.ApplicationRequestInterceptor;
import middle.ground.http.interceptor.LogInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Map;

/**
 * 核心配置类
 *
 * @author jrl
 * @author jrl
 * @date 2020-12-01
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

	/**
	 * 注册拦截器
	 *
	 * @param registry
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {

		/**
		 * 拦截的路径
		 */
		String[] pathPatterns = {
				"/**"
		};

		/**
		 * 不拦截的路径
		 */
		String[] excludePathPatterns = {
				"/api/admins/login",
				"/doc.html",
				"/document.html",
				"/webjars/**"
		};

		/**
		 * 如果有多个拦截器，多写几个即可
		 */
		registry.addInterceptor(new ApplicationRequestInterceptor()).addPathPatterns(pathPatterns).excludePathPatterns(excludePathPatterns);
		registry.addInterceptor(new LogInterceptor()).addPathPatterns(pathPatterns).excludePathPatterns(excludePathPatterns);
	}

	/**
	 * xss过滤拦截器
	 */
	@Bean
	public FilterRegistrationBean xssFilterRegistrationBean() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new XssFilter());
		filterRegistrationBean.setOrder(1);
		filterRegistrationBean.setEnabled(true);
		filterRegistrationBean.addUrlPatterns("/*");
		Map<String, String> initParameters = Maps.newHashMap();
		initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
		initParameters.put("isIncludeRichText", "true");
		filterRegistrationBean.setInitParameters(initParameters);
		return filterRegistrationBean;
	}
}
